package storage

import (
	"cd-crawler/parser/hupuCBA"
	"cd-crawler/types"
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"time"
)

var MysqlDb *sql.DB
var MysqlDbErr error

const (
	USER_NAME = "root"
	PASS_WORD = "root"
	HOST      = "localhost"
	PORT      = "3306"
	DATABASE  = "my_test"
	CHARSET   = "utf8"
)

// 初始化链接
func init() {

	dbDSN := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s", USER_NAME, PASS_WORD, HOST, PORT, DATABASE, CHARSET)

	// 打开连接失败
	MysqlDb, MysqlDbErr = sql.Open("mysql", dbDSN)
	//defer MysqlDb.Close();
	if MysqlDbErr != nil {
		log.Println("dbDSN: " + dbDSN)
		panic("数据源配置不正确: " + MysqlDbErr.Error())
	}

	// 最大连接数
	MysqlDb.SetMaxOpenConns(100)
	// 闲置连接数
	MysqlDb.SetMaxIdleConns(20)
	// 最大连接周期
	MysqlDb.SetConnMaxLifetime(100 * time.Second)

	if MysqlDbErr = MysqlDb.Ping(); nil != MysqlDbErr {
		panic("数据库链接失败: " + MysqlDbErr.Error())
	}

}

// 插入数据
func InsertToDB(item types.Item) {

	playerDetail := item.Payload.(hupuCBA.Player)

	ret, _ := MysqlDb.Exec("replace into cba_player "+
		"(player_id, url, name, role, number, height, weight, birthday,"+
		" team, nation, school, native, score, rebound, block)"+
		"values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
		item.Id, item.Url, playerDetail.Name, playerDetail.Role, playerDetail.Number,
		playerDetail.Height, playerDetail.Weight, playerDetail.Birthday, playerDetail.Team,
		playerDetail.Nation, playerDetail.School, playerDetail.Native, playerDetail.Score,
		playerDetail.Rebound, playerDetail.Block)

	//插入数据的主键id
	lastInsertID, _ := ret.LastInsertId()
	log.Println("LastInsertID:", lastInsertID)
	//
	////影响行数
	//rowsaffected,_ := ret.RowsAffected()
	//fmt.Println("RowsAffected:",rowsaffected)

}
